<template>
  <div class="u-page u-page-process-bg u-box">
    <!-- 标题 -->
    <div class="u-cl-white u-pt-20 u-pb-20">
      <div class="u-fz-26 u-font-bold">
        <span style="color: red">{{ form.workSubject }}</span
        >项目成果
      </div>
      <div class="u-number u-pb-10 u-pt-10">
        请于<span style="color: red">{{ form.deliveryDate }}</span
        >前（含当天）提交第<span style="color: red">{{
          form.subTaskSortNum
        }}</span
        >期<span style="color: red"
          >({{ form.subTaskSortNum }}/{{ form.totalPeriods }})</span
        >工作成果。
      </div>
    </div>

    <!-- 表单 -->
    <div
      class="rule-form rule-form-input-right u-box u-radius-lg u-shadow u-bcl-white"
    >
      <div class="see_template" @click="showTaskDetail">
        点击查看项目实施计划
      </div>
      <u-form ref="uForm" :model="form">
        <u-form-item
          :label="'第' + form.subTaskSortNum + '期'"
          label-position="top"
        >
        </u-form-item>

        <u-form-item label="工作内容与交付标准" label-position="top">
          <div class="u-text-left">{{ form.contentAndRequire }}</div>
        </u-form-item>

        <u-form-item label="本期佣金(元)">
          <div class="u-text-right">{{ form.subTaskPrice }}</div>
        </u-form-item>

        <u-form-item label="交付日期">
          <div class="u-text-right">{{ form.deliveryDate }}</div>
          <div class="Tips" v-if="isOvertime">
            <span style="color: #f02323" v-html="TipInfo"></span>
          </div>
        </u-form-item>

        <div
          v-for="(formItem, index) in taskResultList"
          :key="index"
          style="margin-top: 10rpx"
        >
          <u-form-item
            :label="'第' + formItem.sort + '次工作成果'"
            label-position="top"
            :border-bottom="false"
          >
            <u-input
              v-if="formItem.isEdit"
              type="textarea"
              placeholder="请按照实施计划的工作内容和交付标准提交工作成果。"
              maxlength="-1"
              height="150"
              v-model="formItem.result"
            ></u-input>
            <div class="u-text-left" v-else>{{ formItem.result }}</div>
          </u-form-item>

          <u-form-item
            :label="'第' + formItem.sort + '次返修意见'"
            label-position="top"
            v-if="formItem.remark"
          >
            <div class="u-text-left">{{ formItem.remark }}</div>
          </u-form-item>
        </div>

        <div class="Tips">
          <span style="color: #f02323"
            >*您只有2次返修机会，每一次的返修都将影响到用户对工作成果的满意度（验收成果的满意度将直接决定实际能拿到的项目佣金额度），请谨慎提交。</span
          >
        </div>
      </u-form>

      <!-- 按钮 -->
      <div style="margin-top: 40rpx">
        <u-button
          type="primary"
          :disabled="isClick"
          shape="circle"
          @click="submit"
        >
          提交
        </u-button>
      </div>

      <div style="margin-top: 20rpx">
        <u-button
          type="info"
          :disabled="isClick"
          shape="circle"
          @click="cancel"
        >
          返回
        </u-button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        workSubject: "-无-", // 项目名称
        returnNum: "", // 返修次数
        subTaskSortNum: "-无-", // 第几期
        contentAndRequire: "-无-", // 工作内容与交付标准
        deliveryDate: "-无-", // 交付日期
        subTaskPrice: "-无-", // 本期佣金
        totalPeriods: "-无-", // 总期数
        initiatorId: "", // 发起人id
        initiatorName: "", // 发起人昵称
        partnerId: "", // 拍档id
        partnerName: "", // 拍档昵称
        deliveryId: "", // 交付id
      },
      taskResultList: [], // 工作成果、返修意见以及附件(包含返修的)
      isBack: false, // 是否为返修
      isClick: false, // 提交按钮是否可点击，默认可点击
      isOvertime: false,
      TipInfo: "",
      today: "",
      taskNumber: "",
    };
  },

  onLoad(options) {
    //未登录跳转到登录页面
    const loginRes = this.checkLogin();
    if (!loginRes) {
      return false;
    }
    this.taskNumber = options.taskNumber;
    this.form.deliveryId = options.deliveryId;
    // 删除数组的第一个空元素
    this.taskResultList.splice(0, 1);
  },

  onUnload() {},

  mounted() {
    this.initFormData();
  },

  onReady() {},

  methods: {
    /**
     * 初始化表单数据
     */
    async initFormData() {
      uni.showLoading({
        mask: true,
      });
      this.isClick = true;
      const userInfo = uni.getStorageSync("userInfo");
      const requestData = {
        systemid: "meily",
        url: "/expert/delivery/detail",
        userId: userInfo.userId,
        taskNumber: this.taskNumber,
        deliveryId: this.form.deliveryId,
        editTag: "isEdit", // 工作成果是否可以编辑
        loading: false, // 默认发起请求会有一个全局的Loading，设置false可去掉
      };
      let result = await this.$u.api.unifyMiniRest(requestData);
      const { code, data, taskResultList, msg } = JSON.parse(
        JSON.stringify(result)
      );
      if (code == "200") {
        // 业务数据
        const {
          initiatorId,
          initiatorName,
          partnerId,
          partnerName,
          workSubject,
          subTaskSortNum,
          contentAndRequire,
          subTaskPrice,
          totalPeriods,
          deliveryDate,
          returnNum,
          deliveryId,
        } = data;

        this.form.initiatorId = initiatorId;
        this.form.initiatorName = initiatorName;
        this.form.partnerId = partnerId;
        this.form.partnerName = partnerName;
        this.form.workSubject = workSubject;
        this.form.subTaskSortNum = subTaskSortNum;
        this.form.contentAndRequire = contentAndRequire;
        this.form.subTaskPrice = subTaskPrice;
        this.form.totalPeriods = totalPeriods;
        this.form.deliveryDate = deliveryDate;
        this.form.returnNum = returnNum;
        this.form.deliveryId = deliveryId;

        // 工作成果、返修意见以及附件(包含返修的)
        if (this.isNotNull(taskResultList)) {
          this.taskResultList = taskResultList;
        }

        // 默认日期初始化为今天
        let nowDate = new Date();
        this.today = this.$u.timeFormat(nowDate, "yyyy-mm-dd"); // 将格式转为 yyyy-MM-dd

        // 计算日期差，判断是否超期，返回天数差（大于0：今天 > 交付日期）
        let diff = this.comparisonDate(this.today, this.form.deliveryDate);
        if (diff > 0) {
          this.isOvertime = true;
          this.TipInfo = "当前已超时" + diff + "天";
        }
        // 退回次数大于零，表示返修
        if (Number(this.form.returnNum) > 0) {
          this.isBack = true;
        }
        uni.hideLoading();
        // 设置按钮为可点击
        this.isClick = false;
      } else {
        uni.hideLoading();
        this.$u.toast(msg);
        // 设置按钮为可点击
        this.isClick = false;
      }
    },

    /**
     * 提交流程
     */
    async submit() {
      let taskResult = this.taskResultList.slice(-1)[0];
      // 判断任务成果 内容是否为空
      if (!taskResult.result) {
        this.$u.toast("请填写工作成果！");
        return;
      }
      uni.showLoading({ mask: true });
      this.isClick = true;

      const userInfo = uni.getStorageSync("userInfo");
      const requestData = {
        systemid: "meily",
        url: "/expert/delivery/submit/partner",
        partnerId: userInfo.userId,
        partnerName: userInfo.nickName,
        taskNumber: this.taskNumber,
        taskResult: taskResult,
        deliveryId: this.form.deliveryId,
        initiatorId: this.form.initiatorId, // 发起人id
        loading: false, // 默认发起请求会有一个全局的Loading，设置false可去掉
      };
      try {
        let result = await this.$u.api.unifyMiniRest(requestData);
        if (result.code == "200") {
          uni.hideLoading();
          this.isClick = false;
          uni.reLaunch({
            url:
              "/pages_private_scene1/ExpertCooperate/common/result?mode=41&taskNumber=" +
              this.taskNumber +
              "&workSubject=" +
              this.form.workSubject +
              "&initiatorName=" +
              this.form.initiatorName +
              "&subTaskSortNum=" +
              this.form.subTaskSortNum +
              "&totalPeriods=" +
              this.form.totalPeriods,
          });
        } else {
          uni.hideLoading();
          this.isClick = false;
          this.$u.toast(result.msg);
        }
      } catch (error) {
        uni.hideLoading();
        this.isClick = false;
        this.$u.toast("提交失败，请稍后重试");
      }
    },

    /**
     * 点击查看项目实施计划（用户写的实施计划）
     */
    async showTaskDetail() {
      await this.$u.route(
        "/pages_private_scene1/ExpertCooperate/partnerWorkPlan?taskNumber=" +
          this.taskNumber +
          "&pubPlan=1&userId=" +
          this.form.partnerId +
          "&subject=" +
          this.form.workSubject
      );
    },

    async cancel() {
      this.goBack();
    },

    /**
     * 计算日期差
     * @param {string} startTime - 开始日期（格式：YYYY-MM-DD）
     * @param {string} endTime - 结束日期（格式：YYYY-MM-DD）
     * @returns {number} - 返回天数差（大于0：开始日期 > 结束日期）
     */
    comparisonDate(startTime, endTime) {
      const start_date = new Date(startTime);
      const end_date = new Date(endTime);
      const ms = start_date - end_date;
      return Math.floor(ms / (1000 * 60 * 60 * 24));
    },
  },
};
</script>

<style lang="scss" scoped>
.Tips {
  font-size: 22 rpx;
  line-height: 24 rpx;
  margin-top: 12 rpx;
  color: #9a9a9a;
  padding: 0;
  margin: 0;
  word-break: break-all;
  -webkit-overflow-scrolling: touch;
  -webkit-tap-highlight-color: transparent;
  text-size-adjust: 100%;
  text-align: right !important;
  box-sizing: border-box;
}

.see_template {
  text-align: center;
  color: red;
  text-decoration: underline;
  padding-top: 20 rpx;
}
</style>
